#include <SD.h>

const int CardDetect = A2;     // the card detect pin
const int statusLED = 5;       // Green Status LED on pin 5
const int file_flush = 2;      // Force data write to file after x seconds 

File myFile;

// Struct to hold config info from config.txt file
struct {
  unsigned int baud;    // baud rate
  char fileprefix[20];  // filename prefix  
  char filename[20];    // filename to log data
} config;

unsigned long currentTime;
unsigned long cloopTime;

void setup()
{
  int i;
  pinMode(CardDetect, INPUT);  // Card Detect
  pinMode(statusLED, OUTPUT);  // Status LED
  
  // Default config settings - override with config file "config.txt" if required
  strcpy(config.fileprefix, "LOG.");  
  strcpy(config.filename, "LOG.001");
  
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
  pinMode(10, OUTPUT); 
    
  if(!digitalRead(CardDetect))
  {
    // CardDetect LOW - a card is inserted 
    if (!SD.begin(10)) {
      return;
    }
    read_config_file();

    Serial.begin(115200);
    openlogfile();
  }
  else
  {
	while(1);
  }
  Serial.write(0);
  
}

void loop()
{  
   while(Serial.available())
    myFile.write(Serial.read());
}

void openlogfile()
{
    // Search for next log filename
    get_new_logfile();    
    
    myFile = SD.open(config.filename, FILE_WRITE);

    // if the file opened okay, output the name
    if (myFile) 
    {
      Serial.print("Log file: ");
      Serial.print(config.filename);
    }  
    else 
    {
      // if the file didn't open, print an error:
      Serial.print("Error opening log file: ");
      Serial.println(config.filename);      
    }  
}  


